#include <exception>
#include <iostream>

#include <QCoreApplication>
#include <QDir>

#include "daemon.h"
#include "daemonerror.h"
#include "filesystemerror.h"
#include "xmlerror.h"

using namespace Tubox;
using std::cout;
using std::cerr;
using std::endl;
using std::exception;

class TuboxApp : public QCoreApplication {
public:
	TuboxApp(int argc, char** argv) : QCoreApplication(argc,argv) { }

	bool init(Daemon* _daemon) {
		daemon = _daemon;
		return daemon->askLogin();
	}

	void finalize() {
		if(daemon) delete daemon;
	}

	bool notify(QObject* rec, QEvent* ev) {
		try	{
			return QCoreApplication::notify(rec,ev);
		}
		catch(DaemonError& e) {
			cerr << e.what() << endl;
			cerr << "Status returned: " << e.getStatus() << endl;
		}
		catch(XmlError& e) {
			cerr << e.what() << endl;
			cerr << "XML:\n" << e.getXml().toStdString() << endl;
		}
		catch(FileSystemError& e) {
			cerr << e.what() << endl;
			cerr <<"File:\n" << e.getFile().getFullPath().toStdString() << endl;
		}
		catch(...) {
			cerr << "Dont know man" << endl;
		}
		return false;
	}

private:
	Daemon* daemon;
};

int main(int argc, char** argv) {
	TuboxApp tboxApp(argc,argv);
	cout << "Tubox daemon will try to load configuration file and initiate." << endl;
	try {
		Daemon* daemon = new Daemon(QDir::homePath() + "/.tuboxconfig");
		if(!tboxApp.init(daemon)) {
			throw DaemonError("AskLogin fail");
		}
	}
	catch(DaemonError& e) {
		cerr << e.what() << endl;
		return 1;
	}
	catch(...) {
		cerr << "Really unknown error!" << endl;
		return 666;
  }
	return tboxApp.exec();
}
